﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using TestWebApp.DataAccess.Models;

namespace TestWebApp.DataAccess.Common
{
    // TODO: Tests
    public class Repository<T> : IRepository<T> where T : class
    {
        private EmployeeContext _db;
        private readonly DbSet<T> _dbSet;

        public Repository()
        {
            _db = new EmployeeContext();
            _dbSet = _db.Set<T>();
        }

        public IEnumerable<T> GetAll()
        {
            return _dbSet.AsNoTracking().ToList();
        }

        public T GetById(object id)
        {
            return _dbSet.Find(id);
        }

        public T Insert(T obj)
        {
            return _dbSet.Add(obj);
        }

        public T Update(T obj)
        {
            _db.Entry(obj).State = EntityState.Modified;
            return obj;
        }

        public void DeleteById(object id)
        {
            T getObjById = _dbSet.Find(id);
            _dbSet.Remove(getObjById);
        }

        public void Delete(T obj)
        {
            _dbSet.Remove(obj);
        }

        public void Attach(T obj)
        {
            _dbSet.Attach(obj);
        }

        // Implement unitOfWork
        public void Save()
        {
            _db.SaveChanges();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this._db != null)
                {
                    this._db.Dispose();
                    this._db = null;
                }
            }
        }
    }
}
